﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace IRRemoteControl
{
    public class BinaryIREncoder
    {
        RawIREncoder encoder;
        double[] lead;
        double[] zero;
        double[] one;

        public BinaryIREncoder(int carrierWaveFrequency, double[] lead, double[] zero, double[] one)
        {
            this.encoder = new RawIREncoder(carrierWaveFrequency);
            this.lead = lead;
            this.zero = zero;
            this.one = one;
        }

        public void SendCommandBytes(params byte[] bytes)
        {
            var pwls = new List<double>();

            pwls.AddRange(lead);

            StringBuilder log = new StringBuilder();
            for (int iBytes = 0; iBytes < bytes.Length; iBytes++)
            {
                
                for (int iBits = 0; iBits < 8; iBits++)
                {
                    pwls.AddRange(((bytes[iBytes] >> (7 - iBits)) & 1) == 1 ? one : zero);
                    log.Append(((bytes[iBytes] >> (7 - iBits)) & 1) == 1 ? "1" : "0");
                }
                log.AppendLine();
            }

            Debug.WriteLine(log.ToString());
            encoder.SendCommand(pwls.ToArray());
        }

        public void SendCommandBits(params byte[] bits)
        {
            var pwls = new List<double>();

            pwls.AddRange(lead);

            foreach (var bit in bits)
            {
                if (bit == 0)
                {
                    pwls.AddRange(zero);
                }
                else if (bit == 1)
                {
                    pwls.AddRange(one);
                }
                else
                {
                    throw new ArgumentException("bits");
                }
            }

            encoder.SendCommand(pwls.ToArray());
        }
    }
}
